<template>
  <div class="permission-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">权限管理</h1>
        <p class="page-description">管理系统角色、权限分配和菜单访问控制</p>
      </div>
      <div class="header-actions">
        <el-alert 
          title="系统内置角色" 
          type="info" 
          description="当前显示的是系统内置角色，与用户管理页面保持一致"
          show-icon
          :closable="false"
        />
      </div>
    </div>

    <!-- 权限管理标签页 -->
    <el-tabs v-model="activeTab" class="permission-tabs">
      <!-- 角色管理 -->
      <el-tab-pane label="角色管理" name="roles">
        <div class="roles-section">
          <el-row :gutter="20">
            <el-col :span="8" v-for="role in roles" :key="role.id">
              <el-card class="role-card" shadow="hover">
                <template #header>
                  <div class="role-header">
                    <div class="role-info">
                      <el-icon :size="24" :color="role.color">
                        <component :is="role.icon" />
                      </el-icon>
                      <div class="role-details">
                        <h3 class="role-name">{{ role.name }}</h3>
                        <p class="role-description">{{ role.description }}</p>
                      </div>
                    </div>
                    <el-dropdown @command="handleRoleCommand" trigger="click">
                      <el-button type="text">
                        <el-icon><MoreFilled /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item :command="`permissions-${role.id}`">
                            <el-icon><Key /></el-icon>
                            查看权限
                          </el-dropdown-item>
                          <el-dropdown-item :command="`users-${role.id}`">
                            <el-icon><User /></el-icon>
                            查看用户
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </template>
                
                <div class="role-content">
                  <div class="role-stats">
                    <div class="stat-item">
                      <span class="stat-label">用户数量</span>
                      <span class="stat-value">{{ role.userCount }}</span>
                    </div>
                    <div class="stat-item">
                      <span class="stat-label">权限数量</span>
                      <span class="stat-value">{{ role.permissionCount }}</span>
                    </div>
                  </div>
                  
                  <div class="role-permissions">
                    <h4>主要权限</h4>
                    <div class="permission-tags">
                      <el-tag 
                        v-for="permission in role.mainPermissions" 
                        :key="permission"
                        size="small"
                        class="permission-tag"
                      >
                        {{ permission }}
                      </el-tag>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>

      <!-- 权限列表 -->
      <el-tab-pane label="权限列表" name="permissions">
        <div class="permissions-section">
          <el-card>
            <template #header>
              <div class="permissions-header">
                <span>系统权限列表</span>
                <el-button type="primary" @click="showCreatePermissionDialog">
                  <el-icon><Plus /></el-icon>
                  新增权限
                </el-button>
              </div>
            </template>
            
            <el-table :data="permissions" stripe>
              <el-table-column prop="name" label="权限名称" width="200" />
              <el-table-column prop="code" label="权限代码" width="200" />
              <el-table-column prop="module" label="所属模块" width="150" />
              <el-table-column prop="type" label="权限类型" width="120">
                <template #default="{ row }">
                  <el-tag :type="getPermissionType(row.type)" size="small">
                    {{ getPermissionTypeText(row.type) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="description" label="描述" show-overflow-tooltip />
              <el-table-column label="操作" width="150">
                <template #default="{ row }">
                  <el-button size="small" type="primary" @click="editPermission(row)">
                    编辑
                  </el-button>
                  <el-button size="small" type="danger" @click="deletePermission(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>
      </el-tab-pane>

      <!-- 菜单管理 -->
      <el-tab-pane label="菜单管理" name="menus">
        <div class="menus-section">
          <el-card>
            <template #header>
              <div class="menus-header">
                <span>系统菜单管理</span>
                <el-button type="primary" @click="showCreateMenuDialog">
                  <el-icon><Plus /></el-icon>
                  新增菜单
                </el-button>
              </div>
            </template>
            
            <el-table 
              :data="menuTree" 
              row-key="id"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
              stripe
            >
              <el-table-column label="菜单名称" min-width="200">
                <template #default="{ row }">
                  <div class="menu-name">
                    <el-icon v-if="row.icon" :size="16">
                      <component :is="row.icon" />
                    </el-icon>
                    <span>{{ row.title }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="path" label="路由路径" width="200" />
              <el-table-column prop="component" label="组件" width="200" />
              <el-table-column label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.hidden ? 'danger' : 'success'" size="small">
                    {{ row.hidden ? '隐藏' : '显示' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="sort" label="排序" width="80" />
              <el-table-column label="操作" width="200">
                <template #default="{ row }">
                  <el-button size="small" type="primary" @click="editMenu(row)">
                    编辑
                  </el-button>
                  <el-button size="small" type="success" @click="addSubMenu(row)">
                    添加子菜单
                  </el-button>
                  <el-button size="small" type="danger" @click="deleteMenu(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 角色权限查看对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="角色权限查看"
      width="60%"
      class="permission-dialog"
    >
      <div v-if="currentRole" class="permission-setting">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
          <h3>角色 "{{ currentRole.name }}" 的权限</h3>
          <el-tag type="warning" size="small">系统预设权限（只读）</el-tag>
        </div>
        <el-tree
          ref="permissionTreeRef"
          :data="permissionTree"
          :props="treeProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="currentRole.permissions"
          :check-strictly="false"
          :disabled="true"
          class="permission-tree"
        >
          <template #default="{ data }">
            <div class="tree-node">
              <span class="node-label">{{ data.label }}</span>
              <span class="node-description">{{ data.description }}</span>
            </div>
          </template>
        </el-tree>
      </div>
      
      <template #footer>
        <el-button @click="permissionDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 系统角色说明对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      title="系统角色说明"
      width="50%"
    >
      <div class="role-info-content">
        <el-alert 
          title="关于系统角色" 
          type="info" 
          :closable="false"
          show-icon
        >
          <template #default>
            <p>系统使用内置角色模式，角色权限由系统预设，不支持自定义修改。</p>
            <p>所有角色管理操作请在"用户管理"页面进行。</p>
          </template>
        </el-alert>
        
        <div style="margin-top: 20px;">
          <h4>当前系统角色：</h4>
          <ul style="margin-top: 10px; padding-left: 20px;">
            <li><strong>超级管理员</strong>：拥有系统所有权限</li>
            <li><strong>数据分析师</strong>：负责数据分析和报表生成</li>
            <li><strong>运营管理员</strong>：管理运营数据和用户</li>
            <li><strong>系统管理员</strong>：负责系统监控和管理</li>
          </ul>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="roleDialogVisible = false">知道了</el-button>
        <el-button type="primary" @click="$router.push('/system/users')">前往用户管理</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  MoreFilled, Key, User, UserFilled, DataAnalysis, Plus
} from '@element-plus/icons-vue'

// 响应式数据
const activeTab = ref('roles')
const permissionDialogVisible = ref(false)
const roleDialogVisible = ref(false)
const isEditingRole = ref(false)
const currentRole = ref(null)
const permissionTreeRef = ref(null)
const roleFormRef = ref(null)

// 角色表单数据
const roleForm = ref({
  name: '',
  code: '',
  description: '',
  icon: 'User',
  color: '#409EFF'
})

// 表单验证规则
const roleFormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色代码', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' }
  ]
}

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'label'
}

// 角色数据
const roles = ref([
  {
    id: 1,
    name: '超级管理员',
    code: 'super_admin',
    description: '拥有系统所有权限',
    icon: 'UserFilled',
    color: '#F56C6C',
    userCount: 1,
    permissionCount: 25,
    mainPermissions: ['用户管理', '系统配置', '数据分析', '报表管理'],
    permissions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  },
  {
    id: 2,
    name: '数据分析师',
    code: 'analyst',
    description: '负责数据分析和报表生成',
    icon: 'DataAnalysis',
    color: '#409EFF',
    userCount: 5,
    permissionCount: 12,
    mainPermissions: ['数据分析', '报表管理', '数据可视化'],
    permissions: [3, 4, 5, 6]
  },
  {
    id: 3,
    name: '普通用户',
    code: 'user',
    description: '基础的系统访问权限',
    icon: 'User',
    color: '#67C23A',
    userCount: 20,
    permissionCount: 5,
    mainPermissions: ['基础查看', '个人设置'],
    permissions: [1, 2]
  }
])

// 权限数据
const permissions = ref([
  { id: 1, name: '用户查看', code: 'user:view', module: '用户管理', type: 'view', description: '查看用户列表' },
  { id: 2, name: '用户编辑', code: 'user:edit', module: '用户管理', type: 'edit', description: '编辑用户信息' },
  { id: 3, name: '数据分析', code: 'analysis:view', module: '数据分析', type: 'view', description: '查看数据分析' },
  { id: 4, name: '报表生成', code: 'report:create', module: '报表管理', type: 'create', description: '生成报表' },
  { id: 5, name: '报表导出', code: 'report:export', module: '报表管理', type: 'export', description: '导出报表' }
])

// 权限树数据
const permissionTree = ref([
  {
    id: 1,
    label: '用户管理',
    description: '用户相关权限',
    children: [
      { id: 11, label: '用户查看', description: '查看用户列表' },
      { id: 12, label: '用户编辑', description: '编辑用户信息' },
      { id: 13, label: '用户删除', description: '删除用户' }
    ]
  },
  {
    id: 2,
    label: '数据分析',
    description: '数据分析相关权限',
    children: [
      { id: 21, label: '销售分析', description: '查看销售数据分析' },
      { id: 22, label: '用户分析', description: '查看用户行为分析' },
      { id: 23, label: '运营分析', description: '查看运营数据分析' }
    ]
  },
  {
    id: 3,
    label: '报表管理',
    description: '报表相关权限',
    children: [
      { id: 31, label: '标准报表', description: '查看标准报表' },
      { id: 32, label: '自定义报表', description: '创建自定义报表' },
      { id: 33, label: '报表导出', description: '导出报表文件' }
    ]
  }
])

// 菜单树数据
const menuTree = ref([
  {
    id: 1,
    title: '数据分析',
    path: '/analysis',
    component: 'Layout',
    icon: 'DataAnalysis',
    hidden: false,
    sort: 1,
    children: [
      { id: 11, title: '销售分析', path: '/analysis/sales', component: 'SalesAnalysis', hidden: false, sort: 1 },
      { id: 12, title: '用户分析', path: '/analysis/user', component: 'UserAnalysis', hidden: false, sort: 2 }
    ]
  },
  {
    id: 2,
    title: '报表系统',
    path: '/reports',
    component: 'Layout',
    icon: 'Document',
    hidden: false,
    sort: 2,
    children: [
      { id: 21, title: '标准报表', path: '/reports/standard', component: 'StandardReports', hidden: false, sort: 1 },
      { id: 22, title: '自定义报表', path: '/reports/custom', component: 'CustomReports', hidden: false, sort: 2 }
    ]
  }
])

// 方法
const showCreateRoleDialog = () => {
  roleDialogVisible.value = true
}

const handleRoleCommand = (command) => {
  const [action, id] = command.split('-')
  const role = roles.value.find(r => r.id === parseInt(id))
  
  switch (action) {
    case 'permissions':
      setRolePermissions(role)
      break
    case 'users':
      viewRoleUsers(role)
      break
  }
}

const editRole = (role) => {
  isEditingRole.value = true
  roleForm.value = { ...role }
  roleDialogVisible.value = true
}

const setRolePermissions = (role) => {
  currentRole.value = role
  permissionDialogVisible.value = true
}


const saveRolePermissions = () => {
  ElMessage.info('系统内置角色的权限为预设权限，不支持修改')
  permissionDialogVisible.value = false
}

const showCreatePermissionDialog = () => {
  ElMessage.info('新增权限功能开发中...')
}

const editPermission = (permission) => {
  ElMessage.info('编辑权限功能开发中...')
}

const deletePermission = (permission) => {
  ElMessage.info('删除权限功能开发中...')
}

const showCreateMenuDialog = () => {
  ElMessage.info('新增菜单功能开发中...')
}

const editMenu = (menu) => {
  ElMessage.info('编辑菜单功能开发中...')
}

const addSubMenu = (menu) => {
  ElMessage.info('添加子菜单功能开发中...')
}

const deleteMenu = (menu) => {
  ElMessage.info('删除菜单功能开发中...')
}

// 查看角色用户
const viewRoleUsers = (role) => {
  ElMessage.info(`查看角色"${role.name}"的用户列表功能开发中...`)
}

const getPermissionType = (type) => {
  const types = {
    view: 'info',
    edit: 'warning',
    create: 'success',
    delete: 'danger',
    export: 'primary'
  }
  return types[type] || 'info'
}

const getPermissionTypeText = (type) => {
  const texts = {
    view: '查看',
    edit: '编辑',
    create: '创建',
    delete: '删除',
    export: '导出'
  }
  return texts[type] || '未知'
}

// 生命周期
onMounted(() => {
  // 初始化数据
  loadRoles()
  loadPermissions()
  loadPermissionTree()
  loadMenuTree()
})

// 数据加载方法
const loadRoles = async () => {
  try {
    const { getRoleList } = await import('@/api/system')
    const response = await getRoleList({ page_size: -1 })
    if (response.success) {
      roles.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('加载角色数据失败:', error)
    ElMessage.error('加载角色数据失败')
  }
}

const loadPermissions = async () => {
  try {
    const { getPermissionList } = await import('@/api/system')
    const response = await getPermissionList()
    if (response.success) {
      permissions.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('加载权限数据失败:', error)
    ElMessage.error('加载权限数据失败')
  }
}

const loadPermissionTree = async () => {
  try {
    const { getPermissionTree } = await import('@/api/system')
    const response = await getPermissionTree()
    if (response.success) {
      permissionTree.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('加载权限树失败:', error)
    ElMessage.error('加载权限树失败')
  }
}

const loadMenuTree = async () => {
  try {
    const { getMenuTree } = await import('@/api/system')
    const response = await getMenuTree()
    if (response.success) {
      menuTree.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('加载菜单数据失败:', error)
    ElMessage.error('加载菜单数据失败')
  }
}
</script>

<style scoped>
.permission-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #303133;
}

.header-content p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.permission-tabs {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.role-card {
  height: 280px;
  margin-bottom: 20px;
}

.role-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.role-info {
  display: flex;
  gap: 12px;
}

.role-details h3 {
  margin: 0 0 4px 0;
  font-size: 16px;
  color: #303133;
}

.role-details p {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

.role-content {
  padding: 16px 0;
}

.role-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.role-permissions h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #606266;
}

.permission-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.permission-tag {
  margin: 0;
}

.permissions-header,
.menus-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.menu-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.permission-setting h3 {
  margin: 0 0 16px 0;
  color: #303133;
}

.permission-tree {
  margin-top: 16px;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.node-label {
  font-weight: 500;
  color: #303133;
}

.node-description {
  font-size: 12px;
  color: #909399;
}

.permission-dialog :deep(.el-dialog__body) {
  max-height: 60vh;
  overflow-y: auto;
}
</style>
